package com.main.messagenotificationmanagement.domain.notification.event;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.main.common.utils.exceptions.StackTraceLog;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import com.main.messagenotificationmanagement.infrastructure.util.MessageRouter;
import com.main.messagenotificationmanagement.interfaces.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RocketMQMessageListener(
        topic = "DefaultEventsTopic",
        consumerGroup = "DefaultConsumerGroup",
        selectorType = SelectorType.TAG,
        selectorExpression = "WEBSOCKET_MSG"
)
@Slf4j
public class WebSocketMsgConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private MessageRouter messageRouter;

    private final StackTraceLog stackTraceLog = new StackTraceLog();
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());  // 仅注册 JavaTime 模块


    public void handleRegisterSuccessEvent(String payload) {
        MessageDTO message = null;
        try {
            // 反序列化 payload 为业务对象
            message = objectMapper.readValue(payload, MessageDTO.class);
            //发送通知
            messageRouter.route(message);
        } catch (JsonProcessingException e) {
            System.err.println("反序列化 payload 失败: " + e.getMessage());
        }
    }


    @Override
    public void onMessage(MessageExt msg) {
        try {
            EventMessage event = objectMapper.readValue(msg.getBody(), EventMessage.class);
            log.info("event.getPayload");
            log.info(event.getPayload());
            handleRegisterSuccessEvent(event.getPayload());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}